import React, { useState, useRef, useEffect } from 'react';
import { useRouter } from 'next/router';
import ChatHeader from './ChatHeader';
import ChatMessage from './ChatMessage';
import ChatInput from './ChatInput';
import { useChatStore } from '@/store/chat';

interface ChatInterfaceProps {
  title: string;
  systemPrompt: string;
  serviceId: string;
}

const ChatInterface: React.FC<ChatInterfaceProps> = ({ 
  title, 
  systemPrompt,
  serviceId,
}) => {
  const router = useRouter();
  const [isSpeakerOn, setIsSpeakerOn] = useState(false);
  const [inputText, setInputText] = useState('');
  const { 
    histories,
    isLoading, 
    error, 
    sendMessage,
    setCurrentService,
  } = useChatStore();
  
  const messages = histories[serviceId] || [];
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const chatContainerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setCurrentService(serviceId);
  }, [serviceId, setCurrentService]);

  const scrollToBottom = () => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const handleSpeakerToggle = () => {
    setIsSpeakerOn(!isSpeakerOn);
  };

  const handleHistoryClick = () => {
    router.push('/chat/history');
  };

  const handleSubmit = async () => {
    if (inputText.trim() && !isLoading) {
      const text = inputText;
      setInputText('');
      await sendMessage(text, systemPrompt);
    }
  };

  return (
    <div className="flex flex-col h-screen bg-gray-50">
      <ChatHeader 
        title={title}
        onSpeakerClick={handleSpeakerToggle}
        isSpeakerOn={isSpeakerOn}
        onHistoryClick={handleHistoryClick}
        serviceId={serviceId}
      />
      <div 
        ref={chatContainerRef}
        className="flex-1 overflow-y-auto scroll-smooth"
      >
        <div className="max-w-3xl mx-auto p-4 space-y-6">
          {messages.map((message) => (
            <ChatMessage 
              key={message.id} 
              text={message.text} 
              isBot={message.isBot}
            />
          ))}
          {isLoading && (
            <div className="flex items-center justify-center py-4">
              <div className="animate-pulse text-gray-500">正在思考...</div>
            </div>
          )}
          {error && (
            <div className="p-4 bg-red-50 text-red-600 rounded-lg text-sm">
              {error}
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>
      </div>
      <ChatInput 
        value={inputText}
        onChange={setInputText}
        onSubmit={handleSubmit}
      />
    </div>
  );
};

export default ChatInterface;